<?php

namespace Home\Controller;

class SceneController extends HomeCoreController {
    
	public $Model = null;

    protected function _initialize(){
		
        parent::_initialize();
		
        $this->Model = D('Scene');
		
    }
	
	public function index(){
		
		$id = I('get.sid');
		
		if(IS_AJAX){
			
			$map['sid'] = $id;
			
			$map['uid'] = session(C('AUTH_KEYS'));
				
			$map['mid'] = session('gid');
			
			$page_size = 10;
			
			$count = $this->Model->where($map)->count();
			
			$min = $this->Model->field('MIN(tid) as tid')->where($map)->find();
			
			$max = $this->Model->field('MAX(tid) as tid')->where($map)->find();
			
			$Page = new \Think\Page($count, $page_size);
			
			$list = $this->Model
				->where($map)
				->order("tid asc")
				->limit($Page->firstRow . ',' . $Page->listRows)
				->select();
				
			foreach($list as $k=>$v){
				
				$text = trim($list[$k]['brief']);
				
				$list[$k]['brief'] = mb_substr($text,0,100,'utf-8');
				
				if($list[$k]['tid'] > $min['tid'] && $list[$k]['tid'] < $max['tid']){
					
					$list[$k]['cj'] = '<span class="grid-command btn-up" title="场景上移">上移</span>&nbsp;&nbsp;';
					
					$list[$k]['cj'] .= '<span class="grid-command btn-down" title="场景下移">下移</span>';
					
				}
				
				if($list[$k]['tid'] == $min['tid'] && $list[$k]['tid'] != $max['tid']){
					
					$list[$k]['cj'] = '<span class="grid-command btn-down" title="场景下移">下移</span>';
				
				}
				
				if($list[$k]['tid'] == $max['tid']  && $list[$k]['tid'] != $min['tid']){
					
					$list[$k]['cj'] = '<span class="grid-command btn-up" title="场景上移">上移</span>&nbsp;&nbsp;';
				
				}
				
				if($list[$k]['tid'] == $max['tid']  && $list[$k]['tid'] == $min['tid']){
					
					$list[$k]['cj'] = '';
				
				}

			}
				
			$str = $this->tojson($list, $count);
			
			echo $str;
			
			exit;
			
        }else{
			
			$list = M('Scripts')->find($id);
			
			$this->assign("scripts", $list);
			
            $this->display();
			
        }
		
    }
	
	public function remove(){
	
		$ids = I('get.ids');
		
		$k = I('get.k');
		
        $map['id'] = array('in', $ids);
		
        $result = $this->Model->where($map)->find();
		
		$m0['sid'] = $result['sid'];
			
		$m0['uid'] = $result['uid'];
			
		$m0['mid'] = $result['mid'];
		
		$max = $this->Model->field('MAX(tid) as tid')->where($m0)->find();
		
		if($k == 'up'){
			
			$m['tid'] = array('lt', $result['tid']);
				
			$m['sid'] = $result['sid'];
				
			$m['uid'] = $result['uid'];
				
			$m['mid'] = $result['mid'];
				
			$up = $this->Model->where($m)->order('tid desc')->limit(0,1)->select();
			
			$maps['id'] = $up[0]['id'];
				
			$up['tid'] = $up[0]['tid'];
			
		}
		
		if($k == 'down'){
			
			$ms['tid'] = array('gt', $result['tid']);
			
			$ms['sid'] = $result['sid'];
			
			$ms['uid'] = $result['uid'];
			
			$ms['mid'] = $result['mid'];
			
			$down = $this->Model->where($ms)->order('tid asc')->limit(0,1)->select();
		
			$maps['id'] = $down[0]['id'];
			
			$down['tid'] = $down[0]['tid'];
			
		}
		
		$results = $this->Model->where($maps)->find();
			
		$maps1['id'] = $results['id'];
			
		$data['tid'] = $result['tid'];
			
		$res = $this->Model->where($maps1)->save($data);
			
		if($res){
			
			if($k == 'up'){
		
				$datas['tid'] = $up['tid']; 
				
			}
			
			if($k == 'down'){
			
				$datas['tid'] = $down['tid']; 
				
			}
				
			$ress = $this->Model->where($map)->save($datas);
				
			if($ress){
					
				echo json_encode(array('info'=>'移动成功', 'status'=>'y'));
					
			}else{
				
				$error = $this->Model->getError();
					
				echo json_encode(array('info'=>$error, 'status'=>'n'));
					
			}
				
		}else{
				
			$error = $this->Model->getError();
					
			echo json_encode(array('info'=>$error, 'status'=>'n'));			
			
		}
				
	}
	
	public function add(){
		
		if(IS_POST){
			
			$post_data = I('post.');
			
			$data = $post_data['department'];
			
			$post_data['pic'] = json_encode($post_data['pic']);
			
			$post_data['department'] = json_encode($post_data['department']);
			
			$post_data['hint'] = json_encode($post_data['hint']);
			
			$max = $this->Model->field('MAX(tid) as tid')->find();
			
			if($max['tid'] == NULL){
				
				$post_data['tid'] = 1;
				
			}else{
			
				$post_data['tid'] = $max['tid'] + 1;
			
			}
			
			$data = $this->Model->create($post_data);
			
			if($data){
				
				$result = $this->Model->update($data);
				
				if($result){
				
					echo json_encode(array('info'=>'操作成功', 'status'=>'y'));
						
				}else{
						
					$error = $this->Model->getError();
						
					echo json_encode(array('info'=>$error, 'status'=>'n'));
				
				}
				
			}else{
				
				$error = $this->Model->getError();
				
				echo json_encode(array('info'=>$error, 'status'=>'n'));
				
			}
					
		}else{
			
			$id = I('get.sid');
			
			$list = M('Scripts')->find($id);
			
			$this->assign("scripts", $list);
			
			$department = json_decode($list['department']);
			
			$this->assign("department", $department);
						
			$this->display();
			
		}
		
	}
	
	public function edit(){
		
		if(IS_POST){
			
			$post_data = I('post.');
			
			$post_data['pic'] = json_encode($post_data['pic']);
			
			$post_data['department'] = json_encode($post_data['department']);
			
			$post_data['hint'] = json_encode($post_data['hint']);
			
			$data=$this->Model->create($post_data);
			
			if($data){
				
				$result = $this->Model->where(array('id'=>$post_data['id']))->update($data);
				
				if($result){
					
					echo json_encode(array('info'=>'操作成功', 'status'=>'y'));
					
				}else{
					
					$error = $this->Model->getError();
					
					echo json_encode(array('info'=>$error, 'status'=>'n'));
					
				}
				
			}else{
				
                $error = $this->Model->getError();
				
                echo json_encode(array('info'=>$error, 'status'=>'n'));
				
			}
			
		}else{
			
			$info=I('get.');
			
			$info = $this->Model->where(array('id'=>$info['id']))->find();
			
			$list = M('Scripts')->find($info['sid']);
			
			$this->assign("scripts", $list);
			
			$pics = str_replace('./', '', json_decode($info['pic']));
				
			foreach($pics as $k=>$v){
					
				$data[$k] = explode(".", $v);
					
				$pic[$k]['pic'] = $v;
					
				$pic[$k]['url'] = $data[$k][0];
					
				$pic[$k]['ext'] = $data[$k][1];
					
			}
				
			$this->assign('pic', $pic);
			
			$department = json_decode($info['department']);
			
			$this->assign("department", $department);
			
			$departments = json_decode($list['department']);
			
			foreach($departments as $ks=>$vs){
				
				$datas[$ks] = $vs;
				
				foreach($department as $k=>$v){
					
					$data[$k] = $v;
					
					if($datas[$ks] == $data[$k]){
						
						unset($datas[$ks]);
						
					}
					
				}
				
				$d = $datas[$ks];
				
			}
			
			$d = array_values($datas);	
			
			$this->assign("departments", $d);
			
			if(!empty($department)){
				
				$map['title'] = array('not in', $department);
				
			}
			
			$hint = json_decode($info['hint']);
			
			$this->assign("hint", $hint);
			
			$count = count($hint);
			
			$this->assign("count", $count);
						
			$this->assign('info', $info);
						
        	$this->display();
			
		}
		
	}
	
	public function uploadify(){
		
		$type = I('post.type');
		
		$targetPath = './Public/scene/';
		
		if(!file_exists($targetPath)){
				
			mkdir($targetPath);
				
		}
		
        $config = array(
            'maxSize' => 272629760,
            'rootPath' => './',
            'savePath' => $targetPath,
            'saveName' => array('uniqid', ''),
            'exts' => array('gif', 'jpg', 'png', 'mp4'),
            'autoSub' => true,
            'subName' => array('date', 'Ymd'),
			'saveName' => array('date', 'YmdHis'),
        );
		
		$verifyToken = md5($_POST['timestamp']);

		if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
		
			$upload = new \Think\Upload($config);
			
			$info = $upload->upload();
			
			if(!$info){
				
				$arr = array(
					'status' => 0,
					'type' => $type,
					'msg' => $upload->getError()
				);
				
			}else{
				
				$ajaxname = $info['Filedata']['savepath'] . $info['Filedata']['savename'];
				
				$arr = array(
					'status' => 1,
					'type' => $type,
					'name' => $info['Filedata']['name'],
					'url' => $ajaxname
				);
				
			}
			
			echo json_encode($arr);
			
			exit;
		
		}
		
    }
	
	public function dels(){
		
		$url = I('post.name');
		
		if($url != ""){
			
    		if(unlink($url)){
				
    			$this->success("删除成功");
				
    		}else{

    			$this->error($url);
				
			}
				
    	}else{
			
    		$this->error("删除失败");
			
		}
		
	}
	
	public function imgdel(){
		
		$map['id'] = I('get.id');
		
		$mid = I('get.mid');
		
		$info = $this->Model->where($map)->find();
		
		if($info){
		
			$url = explode(",", $info['media']);
			
			$mid = $mid - 1;
						
			unlink($url[$mid]);
			
			unset($url[$mid]);
			
			$data['media'] = implode(",", $url);
			
			$res = $this->Model->where($map)->save($data);
						
			if($res){
				
				$this->success('删除成功', U('Home/Scene/edit',array('id'=>$map['id'])));
						
			}else{
				
				$this->error("文件不存在", U('Home/Scene/edit',array('id'=>$map['id'])));

			}
		}else{
			
    		$this->error("删除失败");
			
		}

    }
	
	public function del(){
		
		$ids = I('get.ids');
		
        $map['id'] = array('in', $ids);
		
        $res = $this->Model->where($map)->delete();
		
        if($res){
			
            echo json_encode(array('info'=>'删除成功', 'status'=>'y'));
			
        }else{
			
            $error = $this->Model->getError();
			
			echo json_encode(array('info'=>$error, 'status'=>'n'));
			
        }
		
	}
	
}